package cmpe451.group7.ourcity.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cmpe451.group7.ourcity.dao.MultimediaDAO;
import cmpe451.group7.ourcity.entity.Multimedia;
import cmpe451.group7.ourcity.entity.MultimediaType;
import cmpe451.group7.ourcity.entity.Place;
import cmpe451.group7.ourcity.entity.User;

@Repository("multimediaDAO")
public class MultimediaDAOImpl extends GenericDAOImpl<Multimedia> implements
		MultimediaDAO, Serializable {

	private static final long serialVersionUID = 1L;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public List<Multimedia> findAll() {
		return super.findAll(Multimedia.class);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Multimedia findByID(long id) {
		return super.findByID(Multimedia.class, id);
	}

	@Override
	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public List<Multimedia> findPlaceMultimedia(Place place)
			throws HibernateException {
		Session session = this.getCurrentSession();

		List<Multimedia> media = null;
		Criteria criteria = session.createCriteria(Multimedia.class);
		criteria.addOrder(Order.asc("date"));

		criteria.add(Restrictions.eq("place", place));
		media = criteria.list();

		return media;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Multimedia createMultimedia(User owner, byte[] data,
			String mimeType, MultimediaType type) {
		Session session = this.getCurrentSession();

		Multimedia image = new Multimedia();

		image.setFile(data);
		image.setMimeType(mimeType);
		image.setMultimediaType(type);
		image.setOwner(owner);

		session.save(image);
		//session.flush();


		return image;
	}

	@Override
	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public List<Long> findPlaceMultimediaId(Place place) {
		Session session = this.getCurrentSession();

		List<Multimedia> media = null;
		Criteria criteria = session.createCriteria(Multimedia.class);
		criteria.addOrder(Order.asc("date")).setProjection(Projections.id());

		criteria.add(Restrictions.eq("place", place));
		media = criteria.list();

		List<Long> ids = new ArrayList<Long>(media.size());
		for (Multimedia m : media) {
			ids.add(m.getMultimediaID());
		}
		return ids;
	}

}
